package com.example.springboot.utils;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import com.example.springboot.config.applicationContextNameAware.SpringContextHolder;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/8/5 21:49
 */
public class MailUtil extends AppenderBase<ILoggingEvent> {
    private void sendMail(String title, String content) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        // 设置发送邮件地址
        simpleMailMessage.setFrom("1052031630@qq.com");
        // 设置发送对象的邮件地址
        simpleMailMessage.setTo("528402297@qq.com");
        // 设置主题
        simpleMailMessage.setSubject(title);
        // 设置内容
        simpleMailMessage.setText(content);
        // 拿到对象
        JavaMailSender javaMailSender = SpringContextHolder.getBean(JavaMailSender.class);
        // 发送消息
         javaMailSender.send(simpleMailMessage);
    }

    private static final long INTERVAL = 1000;
    private long lastAlarmTime = 0;

    /**
     * 打印错误日志时会触发此接口
     *
     * @param iLoggingEvent
     */
    @Override
    protected void append(ILoggingEvent iLoggingEvent) {
        if (canAlarm()) {
            sendMail(iLoggingEvent.getLoggerName(), iLoggingEvent.getFormattedMessage());
        }
    }

    private boolean canAlarm() {
        long now = System.currentTimeMillis();
        if (now - lastAlarmTime >= INTERVAL) {
            lastAlarmTime = now;
            return true;
        }
        return false;
    }
}
